﻿using System.Text;

namespace MyTRCP.Common.Models
{
    public class RegionNamePayload : BitWalkableObj
    {
        public byte Id { get; set; }
        public string Name { get; set; } = string.Empty;
        public RegionNamePayload(byte[] data) : base(data)
        {
        }
        public override string ToString()
        {
            return $"RegionName(id:{Id},Name:{Name})";
        }

        public override BitWalker WriteToBitWalker(BitWalker bw)
        {
            bw.WriteBits(Id, 8);
            if (!string.IsNullOrEmpty(Name))
            {
                byte[] chars = Encoding.GetEncoding(936).GetBytes(Name);
                int i = 0;
                int len = chars.Length > 10 ? 10 : chars.Length;
                for (; i < len; i++)
                {
                    bw.WriteBits(chars[i], 8);
                }
                for (; i < 10; i++)
                {
                    bw.WriteBits(0, 8);
                }
            }
            return bw;
        }

        public override BitWalker ReadFromBitWalker(BitWalker bw)
        {
            if (bw.ByteLen < 1)
                throw new ArgumentException("字节数组长度过小（1）", nameof(bw));
            Id = (byte)bw.ReadBits(8);
            if (bw.ByteLen >= 11)
                Name = Encoding.GetEncoding(936).GetString(bw.ReadBytes(10)).Replace("\0", "");
            return bw;
        }
    }
}